package com.itheima.health.intercepter;

import com.itheima.health.common.CookieConstant;
import com.itheima.health.common.MessageConst;
import com.itheima.health.context.BaseText;
import com.itheima.health.exception.BusinessRuntimeException;
import com.itheima.health.pojo.entity.Member;
import com.itheima.health.service.MemberService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class MemberLoginInterceptor implements HandlerInterceptor {
    @Autowired
    private MemberService memberService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //判断当前拦截到的是Controller的方法还是其他资源
        if (!(handler instanceof HandlerMethod)) {
            //当前拦截到的不是动态方法，直接放行
            return true;
        }
        Cookie[] cookies =  request.getCookies();
        if(cookies==null || cookies.length==0){
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            throw new BusinessRuntimeException(MessageConst.LOGIN_FAIL);
        }
        String memberId = "";
        for (Cookie cookie : cookies) {
            if(cookie.getName().equals(CookieConstant.LOGIN_AUTH)){
                memberId = cookie.getValue();
            }
        }
        if(StringUtils.isEmpty(memberId)){
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            throw new BusinessRuntimeException(MessageConst.NEED_LOGIN);
        }
        Member member = memberService.selectById(Integer.valueOf(memberId));
        if(StringUtils.isEmpty(member)){
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            throw new BusinessRuntimeException(MessageConst.NEED_LOGIN);
        }
        BaseText.setCurrentId(member.getId());
        Cookie cookie = new Cookie(CookieConstant.LOGIN_AUTH,member.getId().toString());
        cookie.setPath("/");
        cookie.setMaxAge(360000000);
        response.addCookie(cookie);
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
    }
}
